package com.ecreditpal.audio.netty.message;

import com.ecreditpal.audio.util.BaseUtil;
import com.google.protobuf.MessageLite;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author lifeng
 * @version 1.0 on 2018/7/12.
 */
public class CustomProtobufEncoder extends MessageToByteEncoder<Object> {
    /**
     * Encode a message into a {@link ByteBuf}. This method will be called for each written message that can be handled
     * by this encoder.
     *
     * @param ctx the {@link ChannelHandlerContext} which this {@link MessageToByteEncoder} belongs to
     * @param msg the message to encode
     * @param out the {@link ByteBuf} into which the encoded message will be written
     * @throws Exception is thrown if an error occurs
     */
    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        if (msg instanceof MessageLite) {
            MessageLite m = (MessageLite) msg;
            byte[] body = m.toByteArray();
            byte[] header = encodeHeader(body.length);

            out.writeBytes(header);
            out.writeBytes(body);
        } else {
            byte[] header = encodeHeader(0);
            out.writeBytes(header);
        }

    }


    private byte[] encodeHeader(int bodyLength) {
        return BaseUtil.intToBytesReverse(bodyLength);
    }
}
